from selenium import webdriver
from selenium.webdriver.common.by import By
import cv2
import numpy as np
from PIL import Image
import io
import time

def click_by_image(driver, target_image_path):
    # 1. 获取网页截图
    screenshot = driver.get_screenshot_as_png()
    screenshot = Image.open(io.BytesIO(screenshot))
    screenshot = np.array(screenshot)
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
    
    # 2. 读取目标图片
    target = cv2.imread(target_image_path)
    
    # 3. 模板匹配
    result = cv2.matchTemplate(screenshot, target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    
    # 4. 获取目标图片的尺寸
    h, w = target.shape[:2]
    
    # 5. 计算点击位置（目标图片的中心点）
    click_x = max_loc[0] + w//2
    click_y = max_loc[1] + h//2
    
    # 6. 使用 ActionChains 进行点击
    from selenium.webdriver.common.action_chains import ActionChains
    actions = ActionChains(driver)
    actions.move_by_offset(click_x, click_y).click().perform()
    
    # 7. 重置鼠标位置
    actions.move_by_offset(-click_x, -click_y).perform()

# 使用示例
driver = webdriver.Chrome()
driver.get("你的网页URL")

# 等待页面加载
time.sleep(2)

# 假设你有一个目标图片 'target_button.png'
click_by_image(driver, 'target_button.png')



def click_by_image_with_retry(driver, target_image_path, max_retries=3, threshold=0.8):
    for attempt in range(max_retries):
        try:
            # 获取网页截图
            screenshot = driver.get_screenshot_as_png()
            screenshot = Image.open(io.BytesIO(screenshot))
            screenshot = np.array(screenshot)
            screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
            
            # 读取目标图片
            target = cv2.imread(target_image_path)
            
            # 模板匹配
            result = cv2.matchTemplate(screenshot, target, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
            
            # 检查匹配度
            if max_val < threshold:
                print(f"尝试 {attempt + 1}: 匹配度 {max_val:.2f} 低于阈值 {threshold}")
                time.sleep(1)
                continue
                
            # 计算点击位置
            h, w = target.shape[:2]
            click_x = max_loc[0] + w//2
            click_y = max_loc[1] + h//2
            
            # 执行点击
            actions = ActionChains(driver)
            actions.move_by_offset(click_x, click_y).click().perform()
            actions.move_by_offset(-click_x, -click_y).perform()
            
            return True
            
        except Exception as e:
            print(f"尝试 {attempt + 1} 失败: {str(e)}")
            if attempt == max_retries - 1:
                raise
            time.sleep(1)
    
    return False